package com.yunxitest.yunxitest.item.ethernet

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.os.Looper
import com.yunxitest.yunxitest.Interface.IResultCallback
import com.yunxitest.yunxitest.utils.L

class EthernetBroadcastReceiver() : BroadcastReceiver() {

    var isSuccess=false//回调成功
    var callback:IResultCallback?=null
    constructor(callback: IResultCallback) : this() {
        this.callback=callback
        isSuccess=false
    }
    var NET_ETHERNET = 1
    var NET_WIFI = 2
    var NET_NOCONNECT = 0

    override fun onReceive(context: Context, intent: Intent) {

        val action = intent.action;
        if (action.equals(
                        ConnectivityManager.CONNECTIVITY_ACTION)
                || action.equals(
                        "android.net.conn.CONNECTIVITY_CHANGE")) {

            when (isNetworkAvailable(context)) {
                NET_ETHERNET -> {
                    isSuccess=true
                    callback?.success()
                    L.d("testItem"," NET_ETHERNET success ")
                }
                NET_WIFI -> {
                    isSuccess=true
                    callback?.fail("wifi connect.")
                }
                NET_NOCONNECT -> {
                    isSuccess=true
                    callback?.fail("no net connect .")
                    L.d("testItem"," NET_ETHERNET failed . ")
                }
            }
        }
    }

    private fun isNetworkAvailable(context: Context): Int {
        val connectMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val ethNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET)
        val wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI)


        return if (ethNetInfo != null && ethNetInfo.isConnected()) {
            NET_ETHERNET
        } else if (wifiNetInfo != null && wifiNetInfo.isConnected()) {
            NET_WIFI
        } else {
            NET_NOCONNECT
        }
    }

    fun startReceive() {
        isSuccess=false
        android.os.Handler(Looper.getMainLooper()).postDelayed({
            if(!isSuccess!!){
                callback?.fail("Hdmi1Camera time out")
            }
        },3000)
    }
}